<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <!-- 搜索区域 -->
      <t-form
        v-show="showSearch"
        ref="queryRef"
        :data="queryParams"
        layout="inline"
        reset-type="initial"
        label-width="calc(4em + 12px)"
        class="search-form"
      >
        <t-form-item label="代理商名称" name="agentName">
          <t-input
            v-model="queryParams.agentName"
            placeholder="请输入代理商名称"
            clearable
            @enter="handleQuery"
          />
        </t-form-item>
        <t-form-item label="代理层级" name="level">
          <t-select
            v-model="queryParams.level"
            placeholder="请选择代理层级"
            clearable
            :options="levelOptions"
          />
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            :options="statusOptions"
          />
        </t-form-item>
        <t-form-item label="联系人" name="contactName">
          <t-input
            v-model="queryParams.contactName"
            placeholder="请输入联系人"
            clearable
            @enter="handleQuery"
          />
        </t-form-item>
        <t-form-item label="税号" name="taxNumber">
          <t-input
            v-model="queryParams.taxNumber"
            placeholder="请输入税号"
            clearable
            @enter="handleQuery"
          />
        </t-form-item>
        <t-form-item label-width="0px">
          <t-button theme="primary" @click="handleQuery">
            <template #icon> <search-icon /></template>
            搜索
          </t-button>
          <t-button theme="default" @click="resetQuery">
            <template #icon> <refresh-icon /></template>
            重置
          </t-button>
        </t-form-item>
      </t-form>

      <!-- 表格区域 -->
      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="agentId"
        :data="agentList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        empty="暂无数据"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button
                v-hasPermi="['system:agent:add']"
                theme="primary"
                @click="handleAdd"
                :loading="loading"
              >
                <template #icon> <add-icon /></template>
                新增
              </t-button>

              <t-button
                v-hasPermi="['system:agent:export']"
                theme="default"
                variant="outline"
                @click="handleExport"
                :disabled="agentList.length === 0"
              >
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count" v-if="ids.length > 0">
                已选 {{ ids.length }} 项
              </span>
            </t-col>
            <t-col flex="none">
              <t-button
                theme="default"
                shape="square"
                variant="outline"
                @click="showSearch = !showSearch"
                :title="showSearch ? '隐藏搜索' : '显示搜索'"
              >
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button
                theme="default"
                variant="outline"
                @click="columnControllerVisible = true"
              >
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>

        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <my-link
              v-hasPermi="['system:agent:query']"
              @click.stop="handleDetail(row)"
            >
              <template #prefix-icon><browse-icon /></template>
              详情
            </my-link>
            <my-link
              v-hasPermi="['system:agent:edit']"
              @click.stop="handleUpdate(row)"
              :disabled="row.parentAgentId === row.agentId"
            >
              <template #prefix-icon><edit-icon /></template>
              修改
            </my-link>
            <my-link
              v-hasPermi="['system:agent:commission']"
              @click.stop="handleCommission(row)"
            >
              <template #prefix-icon><money-icon /></template>
              分佣
            </my-link>
            <my-link
              v-hasPermi="['system:agent:remove']"
              size="small"
              @click.stop="handleDelete(row)"
              :disabled="row.parentAgentId === row.agentId"
            >
              <template #prefix-icon><delete-icon /></template>
              删除
            </my-link>
          </t-space>
        </template>
      </t-table>
    </t-space>

    <!-- 添加或修改代理商对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="min(600px, 90%)"
      height="min(500px, 80vh)"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="agentRef.submit()"
    >
      <t-loading :loading="buttonLoading" size="small">
        <t-form
          ref="agentRef"
          label-align="right"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >
          <t-form-item label="父级代理商" name="parentAgentId">
            <t-select
              v-model="form.parentAgentId"
              placeholder="请选择父级代理商"
              :options="parentAgentOptions"
              @change="handleParentAgentChange"
              clearable
            />
          </t-form-item>
          <t-form-item label="代理商名称" name="agentName">
            <t-input
              v-model="form.agentName"
              placeholder="请输入代理商名称"
              clearable
            />
          </t-form-item>
          <t-form-item label="代理层级" name="level">
            <t-input
              :value="getLevelLabel(form.level)"
              placeholder="代理层级"
              readonly
              class="readonly-input"
            />
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-select
              v-model="form.status"
              placeholder="请选择状态"
              clearable
              :options="statusOptions"
            />
          </t-form-item>
          <t-form-item label="代理所属地区" name="region">
            <t-input
              v-model="form.region"
              placeholder="请输入代理所属地区"
              clearable
            />
          </t-form-item>
          <t-form-item label="联系人" name="contactName">
            <t-input
              v-model="form.contactName"
              placeholder="请输入联系人"
              clearable
            />
          </t-form-item>
          <t-form-item label="联系电话" name="contactInfo">
            <t-input
              v-model="form.contactInfo"
              placeholder="请输入联系电话"
              clearable
            />
          </t-form-item>
          <!-- 银行信息分组 -->
          <t-form-item label="开户银行名称" name="bankName">
            <t-input
              v-model="form.bankName"
              placeholder="请输入开户银行名称"
              clearable
            />
          </t-form-item>
          <t-form-item label="账户名称" name="accountName">
            <t-input
              v-model="form.accountName"
              placeholder="请输入账户名称"
              clearable
            />
          </t-form-item>
          <t-form-item label="银行账号" name="bankAccount">
            <t-input
              v-model="form.bankAccount"
              placeholder="请输入银行账号"
              clearable
            />
          </t-form-item>
          <t-form-item label="开户支行" name="bankBranch">
            <t-input
              v-model="form.bankBranch"
              placeholder="请输入开户支行"
              clearable
            />
          </t-form-item>

          <!-- 结算信息分组 -->
          <!-- <t-form-item label="结算周期" name="settlementCycle">
            <t-input-number
              v-model="form.settlementCycle"
              placeholder="请输入结算周期"
              :min="0"
            />
          </t-form-item>
          <t-form-item label="结算费率" name="settlementRate">
            <t-input-number
              v-model="form.settlementRate"
              placeholder="请输入结算费率"
              :min="0"
              :max="100"
              :decimal-places="2"
            />
          </t-form-item> -->
          <t-form-item label="税号" name="taxNumber">
            <t-input
              v-model="form.taxNumber"
              placeholder="请输入税号"
              clearable
            />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 代理商详情对话框 -->
    <t-dialog
      v-model:visible="openView"
      header="代理商详情"
      placement="center"
      width="min(700px, 90%)"
      height="min(600px, 80vh)"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="父级代理商名称">{{ form.parentAgentName || '-' }}</t-descriptions-item>
        <t-descriptions-item label="代理商名称">{{ form.agentName || '-' }}</t-descriptions-item>
        <t-descriptions-item label="代理商编号">{{ form.agentCode || '-' }}</t-descriptions-item>
        <t-descriptions-item label="代理层级">{{ getLevelLabel(form.level) || '-' }}</t-descriptions-item>
        <t-descriptions-item label="状态">{{ form.status === 1 ? '启用' : form.status === 0 ? '禁用' : '-' }}</t-descriptions-item>
        <t-descriptions-item label="代理所属地区">{{ form.region || '-' }}</t-descriptions-item>
        <t-descriptions-item label="联系人">{{ form.contactName || '-' }}</t-descriptions-item>
        <t-descriptions-item label="联系电话">{{ form.contactInfo || '-' }}</t-descriptions-item>
        <t-descriptions-item label="开户银行名称">{{ form.bankName || '-' }}</t-descriptions-item>
        <t-descriptions-item label="账户名称">{{ form.accountName || '-' }}</t-descriptions-item>
        <t-descriptions-item label="银行账号">{{ form.bankAccount || '-' }}</t-descriptions-item>
        <t-descriptions-item label="开户支行">{{ form.bankBranch || '-' }}</t-descriptions-item>
        <!-- <t-descriptions-item label="结算周期">{{ form.settlementCycle || '-' }}</t-descriptions-item>
        <t-descriptions-item label="结算费率">{{ form.settlementRate ? `${form.settlementRate}%` : '-' }}</t-descriptions-item> -->
        <t-descriptions-item label="税号">{{ form.taxNumber || '-' }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ form.createTime ? parseTime(form.createTime) : '-' }}</t-descriptions-item>
        <t-descriptions-item label="更新时间">{{ form.updateTime ? parseTime(form.updateTime) : '-' }}</t-descriptions-item>
      </my-descriptions>
    </t-dialog>

    <!-- 分佣对话框 -->
    <t-dialog
      v-model:visible="openCommission"
      header="分佣设置"
      destroy-on-close
      :close-on-overlay-click="false"
      width="min(500px, 90%)"
      attach="body"
      :confirm-btn="{
        loading: commissionLoading,
      }"
      @confirm="commissionRef.submit()"
    >
      <t-loading :loading="commissionLoading" size="small">
        <t-form
          ref="commissionRef"
          label-align="right"
          :data="commissionForm"
          :rules="commissionRules"
          label-width="calc(5em + 41px)"
          @submit="handleCommissionSubmit"
        >
          <t-form-item label="代理商名称">
            <t-input :value="form.agentName" readonly />
          </t-form-item>
          <t-form-item label="选择产品" name="productId">
            <t-select v-model="commissionForm.productId" placeholder="请选择产品" clearable>
              <t-option label="产品A" value="1" />
              <t-option label="产品B" value="2" />
              <t-option label="产品C" value="3" />
            </t-select>
          </t-form-item>
          <t-form-item label="分佣规则" name="ruleId">
            <t-select v-model="commissionForm.ruleId" placeholder="请选择分佣规则" clearable>
              <t-option label="规则A" value="1" />
              <t-option label="规则B" value="2" />
              <t-option label="规则C" value="3" />
            </t-select>
          </t-form-item>
          <t-form-item label="分佣金额" name="commissionAmount">
            <t-input-number v-model="commissionForm.commissionAmount" placeholder="请输入分佣金额" :min="0" />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'Agent',
});

import type { FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext, SelectValue } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { SysAgentForm, SysAgentQuery, SysAgentVo } from '@/api/system/model/agentModel';
import { listAgent, getAgent, delAgent, addAgent, updateAgent,getEnabledAgents } from '@/api/system/agent';

const { proxy } = getCurrentInstance();

// ==================== 状态管理 ====================
/** 详情对话框可见性 */
const openView = ref(false);
/** 详情加载状态 */
const openViewLoading = ref(false);
/** 表单引用 */
const agentRef = ref<FormInstanceFunctions>();
/** 表单对话框可见性 */
const open = ref(false);
/** 分佣对话框可见性 */
const openCommission = ref(false);
/** 分佣表单引用 */
const commissionRef = ref<FormInstanceFunctions>();
/** 分佣加载状态 */
const commissionLoading = ref(false);
/** 按钮加载状态 */
const buttonLoading = ref(false);
/** 对话框标题 */
const title = ref('');
/** 代理商列表数据 */
const agentList = ref<SysAgentVo[]>([]);
/** 表格加载状态 */
const loading = ref(false);
/** 列配置可见性 */
const columnControllerVisible = ref(false);
/** 搜索区域可见性 */
const showSearch = ref(true);
/** 总数据量 */
const total = ref(0);
/** 选中行ID */
const ids = ref<Array<string | number>>([]);
/** 是否单选 */
const single = ref(true);
/** 是否多选 */
const multiple = ref(true);
// ==================== 选项数据 ====================
/** 代理层级选项 */
const levelOptions = ref([
  { value: 1, label: '一级代理' },
  { value: 2, label: '二级代理' },
  { value: 3, label: '三级代理' }
]);

/** 状态选项 */
const statusOptions = ref([
  { value: 0, label: '禁用' },
  { value: 1, label: '启用' }
]);

// ==================== 表单校验规则 ====================
const rules = ref<Record<string, Array<FormRule>>>({
  parentAgentId: [
    { required: true, message: '父级代理商不能为空' },
    { max: 36, message: '父级代理商ID不能超过36个字符' }
  ],
  agentName: [
    { required: true, message: '代理商名称不能为空' },
    { max: 100, message: '代理商名称不能超过100个字符' }
  ],
  level: [
    { required: true, message: '代理层级不能为空' }
  ],
  status: [
    { max: 1, message: '状态不能超过1个字符' }
  ],
  region: [
    { max: 100, message: '代理所属地区不能超过100个字符' }
  ],
  contactInfo: [
    { required: true, message: '联系电话不能为空' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码格式'
    },
    { max: 255, message: '联系电话不能超过255个字符' }
  ],
  contactName: [
    { required: true, message: '联系人不能为空' },
    { max: 50, message: '联系人不能超过50个字符' }
  ],
  bankName: [
    { max: 100, message: '开户银行名称不能超过100个字符' }
  ],
  accountName: [
    { max: 100, message: '账户名称不能超过100个字符' }
  ],
  bankAccount: [
    { max: 50, message: '银行账号不能超过50个字符' }
  ],
  bankBranch: [
    { max: 100, message: '开户支行不能超过100个字符' }
  ],
  taxNumber: [
    { max: 50, message: '税号不能超过50个字符' }
  ],
});

// ==================== 表格列定义 ====================
const columns = ref<Array<PrimaryTableCol>>([
  {
    title: `选择列`,
    colKey: 'row-select',
    type: 'multiple',
    width: 50,
    align: 'center'
  },
  {
    title: `父级代理商`,
    colKey: 'parentAgentName',
    align: 'center',
    ellipsis: true
  },
  {
    title: `代理商名称`,
    colKey: 'agentName',
    align: 'center',
    ellipsis: true
  },
  {
    title: `代理商编号`,
    colKey: 'agentCode',
    align: 'center'
  },
  {
    title: `代理层级`,
    colKey: 'level',
    align: 'center',
    cell: (h, { row }) => {
      const levelMap: Record<number, string> = { 1: '一级代理', 2: '二级代理', 3: '三级代理' };
      return levelMap[row.level as number] || row.level;
    }
  },
  {
    title: `状态`,
    colKey: 'status',
    align: 'center',
    cell: (h, { row }) => {
      const statusMap: Record<number, string> = { 0: '禁用', 1: '启用' };
      return statusMap[row.status as number] || row.status;
    }
  },
  {
    title: `代理所属地区`,
    colKey: 'region',
    align: 'center',
    ellipsis: true
  },
  {
    title: `联系人`,
    colKey: 'contactName',
    align: 'center',
    ellipsis: true
  },
  {
    title: `联系电话`,
    colKey: 'contactInfo',
    align: 'center',
    ellipsis: true
  },
  {
    title: `开户银行名称`,
    colKey: 'bankName',
    align: 'center',
    ellipsis: true
  },
  {
    title: `账户名称`,
    colKey: 'accountName',
    align: 'center',
    ellipsis: true
  },
  {
    title: `银行账号`,
    colKey: 'bankAccount',
    align: 'center'
  },
  {
    title: `开户支行`,
    colKey: 'bankBranch',
    align: 'center',
    ellipsis: true
  },

  {
    title: `税号`,
    colKey: 'taxNumber',
    align: 'center'
  },
  {
    title: `创建时间`,
    colKey: 'createTime',
    align: 'center',
    minWidth: 112,
    width: 180
  },
  {
    title: `更新时间`,
    colKey: 'updateTime',
    align: 'center',
    minWidth: 112,
    width: 180
  },
  {
    title: `操作`,
    colKey: 'operation',
    align: 'center',
    width: 180,
    fixed: 'right'
  },
]);
// ==================== 表单数据 ====================
/** 表单数据对象 */
const form = ref<SysAgentVo & SysAgentForm>({});
/** 分佣表单数据 */
const commissionForm = ref({
  productId: '',
  ruleId: '',
  commissionAmount: 0
});

/** 分佣表单验证规则 */
const commissionRules = ref<Record<string, Array<FormRule>>>({
  productId: [{ required: true, message: '请选择产品' }],
  ruleId: [{ required: true, message: '请选择分佣规则' }],
  commissionAmount: [{ required: true, message: '请输入分佣金额' }],
});

// ==================== 查询参数 ====================
/** 查询参数对象 */
const queryParams = ref<SysAgentQuery>({
  pageNum: 1,
  pageSize: 10,
  parentAgentId: undefined,
  agentName: undefined,
  level: undefined,
  status: undefined,
  contactName: undefined,
  taxNumber: undefined,
});
// ==================== 分页配置 ====================
/** 分页配置 */
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    showSizer: true,
    pageSizeOptions: [10, 20, 50, 100],
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      fetchParentAgents();
      getList();
    },
  };
});

// ==================== 父级代理商选项 ====================
/** 父级代理商选项列表 */
const parentAgentOptions = ref<Array<{label: string; value: string; level: number; parentAgentId: string}>>([]);

/**
 * 获取可用的父级代理商列表
 */
const fetchParentAgents = async () => {
  try {
    const res = await getEnabledAgents();
    parentAgentOptions.value = res.data.map(item => ({
      label: item.agentName,
      value: item.agentId,
      level: Number(item.level),
      parentAgentId: item.parentAgentId,
    }));
  } catch (error) {
    console.error('获取父级代理商失败:', error);
    proxy.$modal.msgError('获取父级代理商列表失败');
  }
};

// ==================== 工具函数 ====================
/**
 * 获取代理层级的中文标签
 * @param level 代理层级数字
 * @returns 对应的中文标签
 */
const getLevelLabel = (level: number | undefined): string => {
  if (level === undefined) return '';
  const levelMap: Record<number, string> = { 1: '一级代理', 2: '二级代理', 3: '三级代理' };
  return levelMap[level] || level.toString();
};

/**
 * 父级代理商选择变化处理
 * @param value 选择的父级代理商ID
 */
const handleParentAgentChange = (value: SelectValue) => {
  const selectedAgent = parentAgentOptions.value.find(item => item.value === value);

  // 防止选择自己作为父级代理商
  if (form.value.agentId && value === form.value.agentId) {
    proxy.$modal.msgError('不能选择自己作为父级代理商');
    form.value.parentAgentId = undefined;
    return;
  }

  if (selectedAgent) {
    const parentLevel = selectedAgent.level || 0;
    const newLevel = parentLevel + 1;
    const levelLabel = getLevelLabel(newLevel);

    // 新增时不提示，修改时提示
    if (form.value.agentId) {
      // 修改时弹出确认对话框
      proxy.$modal.confirm(
        `是否确认将代理层级设置为「${levelLabel}」？`,
        () => {
          // 用户确认后设置代理层级
          form.value.level = newLevel;
        },
        () => {
          // 用户取消后恢复原来的父级代理商选择
          form.value.parentAgentId = undefined;
        }
      );
    } else {
      // 新增时直接设置代理层级，不提示
      form.value.level = newLevel;
    }
  } else {
    // 如果没有选择父级代理商，清空代理层级
    form.value.level = undefined;
  }
};




/** 查询代理商列表 */
function getList() {
  loading.value = true;
  fetchParentAgents();
  listAgent(queryParams.value)
    .then((response) => {
      agentList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {
    status: 1 // 新增时默认状态为启用
  };
  proxy.resetForm('agentRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;

  // 默认禁用状态
  single.value = selection.length !== 1;
  multiple.value = !selection.length;

  // 如果选择了单条数据，检查 parentAgentId 是否等于 id
  if (selection.length === 1) {
    const selectedAgent = agentList.value.find(item => item.agentId === selection[0]);
    if (selectedAgent && selectedAgent.parentAgentId === selectedAgent.agentId) {
      single.value = true; // 禁用修改按钮
      multiple.value = true; // 禁用删除按钮
    }
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加代理商';
}

/** 详情按钮操作 */
function handleDetail(row: SysAgentVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const agentId = row.agentId;
  getAgent(agentId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: SysAgentVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改代理商';
  const agentId = row?.agentId || ids.value.at(0);
  getAgent(agentId?.toString()).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.agentId) {
      updateAgent(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addAgent(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 分佣按钮操作 */
function handleCommission(row: SysAgentVo) {
  commissionForm.value = {
    productId: '',
    ruleId: '',
    commissionAmount: 0
  };
  form.value = { ...row };
  openCommission.value = true;
}

/** 分佣提交 */
function handleCommissionSubmit({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    commissionLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('分佣处理中...');
    
    // 这里可以添加实际的分佣逻辑
    setTimeout(() => {
      proxy.$modal.msgSuccess('分佣成功');
      openCommission.value = false;
      commissionLoading.value = false;
      proxy.$modal.msgClose(msgLoading);
    }, 1000);
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: SysAgentVo) {
  const agentIds = row?.agentId || ids.value;
  // Ensure agentIds is properly typed for delAgent (string | string[])
  const delAgentIds = Array.isArray(agentIds)
    ? agentIds.map(id => id.toString())
    : agentIds.toString();

  proxy.$modal.confirm(`是否确认删除代理商编号为${agentIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delAgent(delAgentIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, agentIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/agent/export',
    {
      ...queryParams.value,
    },
    `agent_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
